package com.tbl.modules.wms.controller.move;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.*;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.entity.move.MoveStorage;
import com.tbl.modules.wms.entity.move.MoveStorageDetail;
import com.tbl.modules.wms.service.allo.AllocationService;
import com.tbl.modules.wms.service.baseinfo.*;
import com.tbl.modules.wms.service.instorage.InstorageDetailService;
import com.tbl.modules.wms.service.move.MoveStorageDetailService;
import com.tbl.modules.wms.service.move.MoveStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 移库入库控制层
 * @author 70486
 */
@Controller
@RequestMapping("/movein")
public class MoveInController extends AbstractController {

    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 移库处理-移库主表
     */
    @Autowired
    private MoveStorageService moveStorageService;
    /**
     * 移库处理-移库详情
     */
    @Autowired
    private MoveStorageDetailService moveStorageDetailService;
    /**
     * 库位
     */
    @Autowired
    private ShelfService shelfService;
    /**
     * 仓库
     */
    @Autowired
    private WarehouseService warehouseService;
    /**
     * 行车
     */
    @Autowired
    private CarService carService;
    /**
     * 盘具
     */
    @Autowired
    private DishService dishService;
    /**
     * 厂区服务类
     */
    @Autowired
    private FactoryAreaService factoryAreaService;
    /**
     * 调拨
     */
    @Autowired
    private AllocationService allocationService;
    /**
     * 标签基础表信息
     */
    @Autowired
    private InstorageDetailService instorageDetailService;

    /**
     * 跳转到入库管理列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/move/movein/movein_list");
        return mv;
    }

    /**
     * 移库入库获取列表数据
     * @param queryJsonString 查询条件
     * @return Map<String , Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        //okk
        map.put("org", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        PageUtils utils = moveStorageService.getInDetailList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 点击开始入库，选择仓库和行车
     * @param id 移库单明细主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/storagestart.do")
    public ModelAndView storageStart(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/move/movein/movein_start");
        MoveStorageDetail moveStorageDetail = moveStorageService.getDetailById(id);
        InstorageDetail instorageDetail = instorageDetailService.selectOne(new EntityWrapper<InstorageDetail>().eq("QACODE", moveStorageDetail.getQaCode()));
        
        //移库的厂区和仓库就是当前物料所在的厂区和仓库
        MoveStorage moveStorage = moveStorageService.selectById(moveStorageDetail.getPId());
        List<Warehouse> warehouseList = new ArrayList<>();
        Warehouse warehouse = warehouseService.selectOne(new EntityWrapper<Warehouse>()
                .eq("CODE", moveStorage.getWarehouseCode())
                //仓库
        		.eq("FACTORYCODE", moveStorage.getFactoryCode()));
        if(warehouse!=null) {
            warehouse.setWarehouseCodeName(warehouse.getCode()+"_"+warehouse.getName());
        }
        //行车列表
        List<Car> carList = moveStorageService.getCarList(Objects.requireNonNull(warehouse).getId());
        warehouseList.add(warehouse);
        
        //获得初始化的推荐库位
        String recommendCode;
        List<Shelf> shelfCodeList;
        Dish dish = dishService.selectOne(new EntityWrapper<Dish>().eq("CODE", moveStorageDetail.getDishnumber()));
        List<Shelf> recommendShelfs = shelfService.selectRecommentList(warehouse.getFactoryCode(),warehouse.getCode(), dish.getOuterDiameter(),
                dish.getDrumType(),carList.get(0).getCode(),moveStorageDetail.getOutShelfCode(), carList.size()>0?carList.get(0).getWarehouseArea():"",
                moveStorageDetail.getSalesCode(),dish.getSuperWide(),"黑色".equals(instorageDetail.getColour())||StringUtils.isBlank(instorageDetail.getColour())?0:1);
        
        if(recommendShelfs.size()>0) {
    		recommendCode = recommendShelfs.get(0).getCode();
        }else {
        	//获取未被占用的库位
        	shelfCodeList = shelfService.getRecommendShelf(warehouse.getCode(),warehouse.getFactoryCode(),carList.size()>0?carList.get(0).getWarehouseArea():"");
        	//原所在库位要去掉
        	Iterator<Shelf> sf = shelfCodeList.iterator();
        	while (sf.hasNext()) {
				Shelf shelf = sf.next();
				if(moveStorageDetail.getOutShelfCode().equals(shelf.getCode())) {
					sf.remove();
					break;
				}
			}
        	recommendCode = shelfCodeList.size()>0?shelfCodeList.get(0).getCode():"";
        }
        
        mv.addObject("recommendCode",recommendCode);
        mv.addObject("moveStorageDetailId",id);
        mv.addObject("info", moveStorageDetail);
        mv.addObject("warehouseList", warehouseList);
        mv.addObject("carList", carList);
        return mv;
    }

    /**
     * 仓库与行车确认，行车列表根据选定仓库变化
     * @param moveStorageDetailId 移库单明细主键
     * @param id 仓库主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/warehouseChangeList.do")
    @ResponseBody
    public Map<String, Object> warehouseChangeList(Long moveStorageDetailId,Long id) {
        Map<String, Object> map = new HashMap<>(2);
        String recommendCode;
        Warehouse warehouse = warehouseService.selectById(id);
        MoveStorageDetail moveStorageDetail = moveStorageDetailService.selectById(moveStorageDetailId);
        InstorageDetail instorageDetail = instorageDetailService.selectOne(new EntityWrapper<InstorageDetail>().eq("QACODE", moveStorageDetail.getQaCode()));
        List<Car> carList = carService.selectList(new EntityWrapper<Car>()
                .eq("FACTORYCODE", warehouse.getFactoryCode())
        		.eq("WAREHOUSECODE", warehouse.getCode())
                .eq("STATE", 2));
        Dish dish = dishService.selectOne(new EntityWrapper<Dish>().eq("CODE", moveStorageDetail.getDishnumber()));
        List<Shelf> recommendShelfs = shelfService.selectRecommentList(warehouse.getFactoryCode(),warehouse.getCode(), dish.getOuterDiameter(),
                dish.getDrumType(),carList.get(0).getCode(),moveStorageDetail.getOutShelfCode(), carList.size()>0?carList.get(0).getWarehouseArea():"",
                moveStorageDetail.getSalesCode(),dish.getSuperWide(),"黑色".equals(instorageDetail.getColour())||StringUtils.isBlank(instorageDetail.getColour())?0:1);
        
        if(recommendShelfs.size()>0) {
    		recommendCode = recommendShelfs.get(0).getCode();
        }else {
        	//获取未被占用的库位
            List<Shelf> shelfCodeList = shelfService.getRecommendShelf(warehouse.getCode(),warehouse.getFactoryCode(),
                    carList.size()>0?carList.get(0).getWarehouseArea():"");
        	//原所在库位要去掉
        	Iterator<Shelf> sf = shelfCodeList.iterator();
        	while (sf.hasNext()) {
				Shelf shelf = sf.next();
				if(moveStorageDetail.getOutShelfCode().equals(shelf.getCode())) {
					sf.remove();
					break;
				}
			}
        	recommendCode = shelfCodeList.size()>0?shelfCodeList.get(0).getCode():"";
        }
        
        map.put("list", moveStorageService.getCarList(id));
        //推荐库位
        map.put("recommendCode", recommendCode);
        return map;
    }

    /**
     * 功能描述: 点击开始入库,确认
     * 1.更新仓库，行车，状态信息
     * 2.判断当前状态 （1.未确认 2.已包装  3.入库中  4.入库完成）
     * @param moveStorageDetail 移库单明细
     * @return Map<String,Object> 返回结果集
     */
    @RequestMapping(value = "/updateWarehouseAndCar")
    @ResponseBody
    public Map<String, Object> updateWarehouseAndCar(MoveStorageDetail moveStorageDetail) {
        Map<String, Object> map = new HashMap<>(2);
        String msg;
        Integer state = moveStorageDetailService.selectById(moveStorageDetail.getId()).getState();
        if (state == Constant.INT_FOUR) {
            msg = "已经开始入库操作，请勿重复提交！";
        } else if (state == Constant.INT_FIVE) {
            msg = "入库完成,请勿重复提交！";
        } else {
            moveStorageService.updateDetail(moveStorageDetail);
            map.put("result", true);
            map.put("msg", "提交成功！");
            return map;
        }
        map.put("result", false);
        map.put("msg", msg);
        return map;
    }

    /**
     * 点击入库确认，跳转页面
     * @param id 移库详情主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/storageconfirm.do")
    public ModelAndView storageConfirm(Long id) {
        ModelAndView mv = this.getModelAndView();
        MoveStorageDetail moveStorageDetail = moveStorageDetailService.selectById(id);
        InstorageDetail instorageDetail = instorageDetailService.selectOne(new EntityWrapper<InstorageDetail>().eq("QACODE", moveStorageDetail.getQaCode()));
        String recommendCode;
        Dish dish = dishService.selectOne(new EntityWrapper<Dish>().eq("CODE", moveStorageDetail.getDishnumber()));
        Car car = carService.selectOne(new EntityWrapper<Car>().eq("CODE", moveStorageDetail.getInCarCode()));
        List<Shelf> recommendShelfs = shelfService.selectRecommentList(moveStorageDetail.getOrg(),moveStorageDetail.getWarehouseCode(),dish.getOuterDiameter(),
                dish.getDrumType(),car.getCode(), moveStorageDetail.getOutShelfCode(),car.getWarehouseArea(),moveStorageDetail.getSalesCode(),
                dish.getSuperWide(),"黑色".equals(instorageDetail.getColour())||StringUtils.isBlank(instorageDetail.getColour()) ? 0 : 1);
        
        if(recommendShelfs.size()>0) {
    		recommendCode = recommendShelfs.get(0).getCode();
        }else {
        	//获取未被占用的库位
            List<Shelf> shelfCodeList = shelfService.getRecommendShelf(moveStorageDetail.getWarehouseCode(),moveStorageDetail.getOrg(),car.getWarehouseArea());
        	//原所在库位要去掉
        	Iterator<Shelf> sf = shelfCodeList.iterator();
        	while (sf.hasNext()) {
				Shelf shelf = sf.next();
				if(moveStorageDetail.getOutShelfCode().equals(shelf.getCode())) {
					sf.remove();
					break;
				}
			}
        	recommendCode = shelfCodeList.size() > 0 ? shelfCodeList.get(0).getCode() : "" ;
        }
        
        mv.addObject("info", moveStorageService.getDetailById(id));
        mv.addObject("recommendCode", recommendCode);
        mv.setViewName("techbloom/move/movein/movein_confirm");
        return mv;
    }

    /**
     * 手动入库，跳转页面
     * @param id 移库单明细主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/storageManual.do")
    public ModelAndView storageManual(Long id) {
        ModelAndView mv = this.getModelAndView();
        MoveStorageDetail moveStorageDetail = moveStorageDetailService.selectById(id);
        mv.addObject("info", moveStorageService.getDetailById(id));
        mv.addObject("recommendCode", "");
        mv.addObject("info", moveStorageService.getDetailById(id));
        mv.addObject("warehouseList", allocationService.getWarehouseList(moveStorageDetail.getOrg()));
        mv.addObject("factory", factoryAreaService.selectOne(new EntityWrapper<FactoryArea>().eq("CODE",moveStorageDetail.getOrg())).getName());
        mv.setViewName("techbloom/move/movein/movein_manual_in");
        return mv;
    }

    /**
     * 下拉框选择库位
     * @param warehouseId 仓库主键
     * @param queryString 模糊查询条件
     * @param pageSize 页数
     * @param pageNo 页码
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/selectUnbindShelf.do")
    @ResponseBody
    public Map<String, Object> selectUnbindShelf(Long warehouseId,String queryString,int pageSize,int pageNo) {
        Map<String, Object> map = new HashMap<>(4);
        if (warehouseId != null) {
            map.put("warehouseId", warehouseId);
            map.put("queryString", queryString.toUpperCase());
            PageTbl page = this.getPage();
            page.setPageno(pageNo);
            page.setPagesize(pageSize);
            PageUtils utils = moveStorageService.selectUnbindShelf(page, map);
            page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
            //初始化分页对象
            executePageMap(map, page);
            map.put("result", utils.getList());
            map.put("total", utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        }else{
            map.put("result", "");
            map.put("total", 0);
        }
        return map;
    }

    /**
     * 功能描述:入库确认,点击完成
     * @param moveStorageDetail 移库详情
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/confirmInstorage")
    @ResponseBody
    public Map<String, Object> confirmInstorage(MoveStorageDetail moveStorageDetail) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = false;
        String msg;
        if (moveStorageDetailService.selectById(moveStorageDetail.getId()).getState() == Constant.INT_FIVE) {
            msg = "入库完成,请勿重复提交！";
        } else {
            result = moveStorageService.confirmInstorage(moveStorageDetail.getId(), moveStorageDetail.getShelfId(), getUserId());
            msg = result?"提交成功！":"提交失败！";
        }
        map.put("result", result);
        map.put("msg", msg);
        return map;
    }

    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>(4);
        map.put("ids", StringUtils.stringToInt(request.getParameter("ids")));
        map.put("qaCode", request.getParameter("queryqaCode"));
        map.put("createTime", request.getParameter("querycreateTime"));
        map.put("endTime", request.getParameter("queryendTime"));

        try {
            String sheetName = "移库入库" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("moveCode", "移库单号");
                mapFields.put("inStorageTimeStr", "入库时间");
                mapFields.put("qaCode", "质保单号");
                mapFields.put("batchNo", "批次号");
                mapFields.put("stateStr", "状态");
                mapFields.put("pickManName", "确认人");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("moveCode", "移库单号");
                    } else if ("3".equals(s)) {
                        mapFields.put("inStorageTimeStr", "入库时间");
                    } else if ("4".equals(s)) {
                        mapFields.put("qaCode", "质保单号");
                    } else if ("5".equals(s)) {
                        mapFields.put("batchNo", "批次号");
                    } else if ("6".equals(s)) {
                        mapFields.put("stateStr", "状态");
                    } else if ("7".equals(s)) {
                        mapFields.put("pickManName", "确认人");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, moveStorageService.getMoveInExcelList(map), mapFields, response, "");
            logService.logInsert("移库入库导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
